package pl.mchaniewski.ryneczek.web.user;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.Portfolio;
import pl.mchaniewski.ryneczek.services.PortfolioService;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.utilities.SecurityUtil;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class PortfolioListBean {
    private static final Logger logger = LoggerFactory
            .getLogger(PortfolioListBean.class);
    private PortfolioService portfolioService;
    private SelectedPortfolioBean selectedPortfolioBean;

    /* PostConstruct parameters */
    private List<Portfolio> userPortfolios;

    @Autowired
    public void setPortfolioService(PortfolioService portfolioService) {
        this.portfolioService = portfolioService;
    }

    @Autowired
    public void setSelectedPortfolioBean(
            SelectedPortfolioBean selectedPortfolioBean) {
        this.selectedPortfolioBean = selectedPortfolioBean;
    }

    public Integer getNumberOfPortfolios() {
        return userPortfolios.size();
    }

    public Integer getHowManyCanCreate() {
        return Portfolio.MAXIMUM_PORTFOLIOS - userPortfolios.size();
    }

    public List<Portfolio> getPortfolios() {
        return userPortfolios;
    }

    @PostConstruct
    public void init() {
        UserDetails loggedUser = SecurityUtil.getUserDetails();
        String loggedUsername = (loggedUser != null) ? loggedUser.getUsername()
                : null;
        userPortfolios = portfolioService.findByUsername(loggedUsername);
    }

    public String selectPortfolio(String id) {
        Integer intValue = null;
        try {
            intValue = Integer.parseInt(id);
        } catch (NumberFormatException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could't select portfolio with ID [{}]", id);
            }

            return NavigationUtil.SAME_PAGE;
        }

        try {
            selectedPortfolioBean.setSelectedPortfolioId(getPortfolios().get(
                    intValue).getPortfolioid());
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                Object[] args = { intValue, getPortfolios().size(), ex };
                logger.debug(
                        "Couldn't select portfolio with index [{}]. List size: {}. Exception: {}",
                        args);
            }

            return NavigationUtil.SAME_PAGE;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Portfolio set [{}]",
                    selectedPortfolioBean.getSelectedPortfolioId());
        }
        return NavigationUtil.SAME_PAGE;
    }

}
